package com.bblocks.common.anti_reptile.data.config;


import com.bblocks.common.anti_reptile.data.AntiEsStatConsts;
import com.bblocks.common.anti_reptile.data.bean.EsDslProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ResourceLoader;

import java.io.IOException;
import java.io.InputStream;

/**
 * <p>Project: bb-anti-reptile - DatabaseConfig</p>
 * <p>描述：</p>
 *
 * @Author Zhao [125043150@qq.com]
 * @Date 2024/4/1 11:23
 * @Version 1.0
 * @since 8
 */
@Slf4j
public class EsStatConfig {

    @Bean
    public EsDslProperties esJsonProperties(EsStatProperties properties, ResourceLoader resourceLoader){
        EsDslProperties esJsonProperties = initDefaultEsJsonParams(resourceLoader);
        return esJsonProperties;
    }


    /**
     * 提取默认es查询dsl
     */
    private EsDslProperties initDefaultEsJsonParams(ResourceLoader resourceLoader){
        EsDslProperties esJsonProperties = new EsDslProperties();
        try {
            esJsonProperties.setIpDayUsers(getFileContent(AntiEsStatConsts.EsJson.ip_day_users,resourceLoader));
            esJsonProperties.setIpNologinAccess(getFileContent(AntiEsStatConsts.EsJson.ip_nologin_access,resourceLoader));
            esJsonProperties.setIpNologinAccessQps(getFileContent(AntiEsStatConsts.EsJson.ip_nologin_access_qps,resourceLoader));
            esJsonProperties.setUserAccess(getFileContent(AntiEsStatConsts.EsJson.user_access,resourceLoader));
            esJsonProperties.setUserAccessQps(getFileContent(AntiEsStatConsts.EsJson.user_access_qps,resourceLoader));
        }catch (IOException e){
            log.error("读取默认EsJson失败:",e);
            throw new RuntimeException(e);
        }
        return esJsonProperties;
    }

    private String getFileContent(String name,ResourceLoader resourceLoader) throws IOException{
        org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:static/" + name);
        try(InputStream inputStream = resource.getInputStream()){
            return org.apache.commons.io.IOUtils.toString(inputStream, "UTF-8");
        }
    }
}
